
<template>
  <div class="container dark-theme">
    <!-- 头部导航栏 -->
    <div class="header">
      <div class="back-button" @click="goBack">
        <i class="el-icon-arrow-left"></i> 返回
      </div>
      <div class="title">全部活动</div>
      <div class="header-actions">
        <el-button type="primary" @click="showOrders">
          <i class="el-icon-tickets"></i> 活动记录
        </el-button>
      </div>
    </div>

    <!-- 组织者信息 -->
    <div class="organizer-section">
      <div class="organizer-info">
        <div class="organizer-image">
          <img :src="organizer.images || defaultImage" :alt="organizer.name">
        </div>
        <div class="organizer-details">
          <h2>{{ organizer.name || '未知组织者' }}</h2>
          <p class="description">{{ organizer.description || '暂无描述' }}</p>
          <p class="contact"><i class="el-icon-message"></i> {{ organizer.contact || '暂无联系方式' }}</p>
          <p class="address"><i class="el-icon-location"></i> {{ organizer.address || '暂无地址' }}</p>
        </div>
      </div>
    </div>

    <!-- 活动列表 -->
    <div class="content">
      <div class="activity-grid">
        <div v-for="activity in activitys" :key="activity.id" class="activity-card" @click="viewDetail(activity)">
          <div class="activity-image">
            <img :src="activity.images || defaultImage" :alt="activity.title">
            <div v-if="activity.currentPrice < activity.originalPrice" class="special-tag">特价</div>
            <div v-if="activity.status === 2" class="sold-out-tag">已下架</div>
          </div>
          <div class="activity-info">
            <div class="activity-header">
              <h3>{{ activity.title }}</h3>
            </div>
            <div class="store-info">
              <i class="el-icon-shop"></i>
              <span>{{ activity.organizerName || '未知组织者' }}</span>
            </div>



            <!-- <div class="activity-footer">
              <div class="tags">
                <span v-if="activity.currentPrice < activity.originalPrice" class="tag special">特价</span>
                <span v-if="isNewActivity(activity.createTime)" class="tag new">新房源</span>
                <span v-if="activity.status === 1" class="tag hot">热租</span>
              </div>
            </div> -->

          </div>
        </div>
      </div>
    </div>

    <!-- 活动记录对话框 -->
    <el-dialog title="活动记录" :visible.sync="ordersDialogVisible" width="70%" custom-class="orders-dialog">
      <el-table :data="orders" style="width: 100%" :header-cell-style="{ background: '#002d52', color: '#fff' }"
        :cell-style="{ background: '#fff', color: 'black' }" @selection-change="handleOrderSelectionChange">
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column label="活动图片" width="120">
          <template slot-scope="scope">
            <img :src="scope.row.goodImage || defaultImage" :alt="scope.row.goodTitle || ''" class="activity-img">
          </template>
        </el-table-column>
        <el-table-column prop="order_id" label="订单ID" width="150"></el-table-column>
        <el-table-column prop="goodTitle" label="活动名称"></el-table-column>
        <el-table-column prop="order_status" label="状态" width="100">
          <template slot-scope="scope">
            {{ getOrderStatusText(scope.row.order_status) }}
          </template>
        </el-table-column>
        <el-table-column prop="order_time" label="报名时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.order_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="activity_start_time" label="活动开始时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.activity_start_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="activity_end_time" label="活动结束时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.activity_end_time) }}
          </template>
        </el-table-column>
      </el-table>
      <div class="orders-footer">
        <el-button type="danger" size="small" @click="refundOrder"
          :disabled="!selectedOrderItems.length || selectedOrderItems.every(item => item.order_status !== 1)"
          title="仅可取消状态为'已报名'的活动">
          批量取消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'OrganizerDetail',
  data() {
    return {
      organizer: {
        id: null,
        name: '',
        contact: '',
        address: '',
        description: '',
        images: ''
      },
      activitys: [],
      orders: [],
      user: null,
      ordersDialogVisible: false,
      ordersTotalPrice: 0,
      selectedOrderItems: [],
      defaultImage: 'https://via.placeholder.com/150',
      imageBaseUrl: 'http://localhost:8089',
      isLoadingOrders: false,
      isRefunding: false,
    };
  },
  created() {
    this.fetchUser();
    this.fetchOrganizer();
    this.fetchActivitys();
  },
  methods: {
    async fetchUser() {
      try {
        const { data: userData } = await axios.get('/users/user/basic', {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
        });
        if (userData.success && userData.data) {
          this.user = userData.data;
        } else {
          this.$message.error('获取用户信息失败：无有效数据');
        }
      } catch (error) {
        this.$message.error('获取用户信息失败');
        console.error('获取用户信息失败:', error);
      }
    },

    async fetchOrganizer() {
      const organizerId = this.$route.params.id; // 改为 id
      if (!organizerId) {
        this.$message.error('组织者ID缺失，请检查路由');
        return;
      }
      axios.get(`/commodity/organizer/${organizerId}`, {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
      }).then((res) => {
        if (res.data.success) {
          this.organizer = res.data.data
        } else {
          Message('组织者请求失败')
        }
      }).catch((err) => {
        console.log('组织者请求失败', err)
        Message('组织者请求失败')
      })
    },


    // async fetchActivitys() {
    //   const organizerId = this.$route.params.id; // 改为 id
    //   if (!organizerId) {
    //     this.$message.error('组织者ID缺失，请检查路由');
    //     return;
    //   }
    //   axios.get().get(`/commodity/activity/listOfOrganizer/${organizerId}`, {
    //     headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
    //   }).then((res) => {
    //     if (res.data.success) {
    //       const activitys = res.data.data
    //       activitys.map(async (activity) => {
    //         let organizerName = this.organizer.name || '未知组织者';
    //         if (!organizerName || organizerName == '未知组织者') {
    //           try {
    //             const organizerResponse = await axios.get(`/commodity/organizer/${activity.organizerId}`, {
    //               headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
    //             });
    //             if (organizerResponse.data.success && organizerResponse.data.data) {
    //               organizerName = organizerResponse.data.data.name || `组织者${activity.organizerId}`;
    //             }
    //           } catch (organizerError) {
    //             console.error(`获取组织者${activity.organizerId}信息失败:`, organizerError);
    //           }
    //         }
    //         return {
    //           ...activity,
    //           organizerName,
    //         };
    //       })
    //     } else {
    //       Message('活动请求失败')
    //     }
    //   }).then((err) => {
    //     Message('活动请求失败')
    //     console.log('活动请求失败', err)
    //   })
    // },

    async fetchActivitys() {
      const organizerId = this.$route.params.id; // 改为 id
      if (!organizerId) {
        this.$message.error('组织者ID缺失，请检查路由');
        return;
      }
      try {
        const response = await axios.get(`/commodity/activity/listOfOrganizer/${organizerId}`, {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
        });
        if (response.data.success) {
          this.activitys = response.data.data;
          this.activitys = await Promise.all(
            this.activitys.map(async (activity) => {
              let organizerName = this.organizer.name || '未知组织者';
              if (!organizerName || organizerName === '未知组织者') {
                try {
                  const organizerResponse = await axios.get(`/commodity/organizer/${activity.organizerId}`, {
                    headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
                  });
                  if (organizerResponse.data.success && organizerResponse.data.data) {
                    organizerName = organizerResponse.data.data.name || `组织者${activity.organizerId}`;
                  }
                } catch (organizerError) {
                  console.error(`获取组织者${activity.organizerId}信息失败:`, organizerError);
                }
              }
              return {
                ...activity,
                organizerName,
              };
            })
          );
        } else {
          this.$message.error(response.data.errorMsg || '获取活动列表失败');
        }
      } catch (error) {
        this.$message.error('网络错误，请稍后重试');
        console.error('获取活动列表失败:', error);
      }
    },
    async fetchOrders() {
      if (!this.user?.id) {
        this.$message.error('请先登录');
        return;
      }
      if (this.isLoadingOrders) return;
      this.isLoadingOrders = true;
      const userId = this.user.id;
      try {
        const response = await axios.get(`/commodity/activity-order/list/allOrder?userId=${userId}`, {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
        });
        if (response.data.success) {
          if (!response.data.data || response.data.data.length === 0) {
            this.$message.info('暂无活动记录');
            this.orders = [];
            this.updateOrdersTotal();
            return;
          }
          this.orders = response.data.data.map((order) => {
            const calculatedTotal = order.currentPrice * order.amount;
            if (order.total !== calculatedTotal) {
              console.warn(`订单 ${order.id} 总价异常：后端返回 ${order.total}，应为 ${calculatedTotal}`);
            }
            return {
              order_id: order.id,
              goodTitle: order.title || '未知活动',
              amount: order.amount || 1,
              currentPrice: order.currentPrice || 0,
              totalPrice: calculatedTotal,
              goodImage: order.images,
              order_status: order.status !== null ? order.status : -1,
              order_time: order.createTime || new Date().toISOString(),
              activity_start_time: order.activityStartTime || new Date().toISOString(),
              activity_end_time: order.activityEndTime || new Date().toISOString(),
            };
          });
          this.updateOrdersTotal();
        } else {
          this.$message.error(response.data.errorMsg || '获取活动记录失败');
        }
      } catch (error) {
        this.$message.error('网络错误，请稍后重试');
        console.error('获取活动记录失败:', error);
      } finally {
        this.isLoadingOrders = false;
      }
    },
    goBack() {
      this.$router.go(-1);
    },
    viewDetail(activity) {
      this.$router.push(`/activity-detail/${activity.id}`);
    },
    showOrders() {
      this.ordersDialogVisible = true;
      this.fetchOrders();
    },
    async refundOrder() {
      if (!this.selectedOrderItems.length) {
        this.$message.warning('请至少选择一个活动记录进行退款');
        return;
      }
      if (this.isRefunding) return;
      this.isRefunding = true;
      this.$confirm(`确定要退款选中的 ${this.selectedOrderItems.length} 个活动记录吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          try {
            const token = localStorage.getItem('token');
            for (const order of this.selectedOrderItems) {
              if (!order.order_id) {
                this.$message.error(`活动记录 ${order.goodTitle} 缺少有效的订单ID`);
                continue;
              }
              const response = await axios.post(
                `/commodity/activity-order/refund?orderId=${order.order_id}`,
                {},
                { headers: { Authorization: `Bearer ${token}` } }
              );
              if (!response.data.success) {
                this.$message.error(`活动记录 ${order.order_id} 退款失败：${response.data.errorMsg || '未知错误'}`);
              } else {
                this.$message.success(`活动记录 ${order.order_id} 退款成功`);
              }
            }
            this.$message.success('退款申请处理完成');
            this.fetchOrders();
          } catch (error) {
            this.$message.error('退款请求失败：' + (error.response?.data?.errorMsg || error.message));
            console.error('退款失败:', error);
          } finally {
            this.isRefunding = false;
          }
        })
        .catch(() => {
          this.$message.info('已取消退款');
          this.isRefunding = false;
        });
    },
    handleOrderSelectionChange(selection) {
      this.selectedOrderItems = selection;
      this.updateOrdersTotal();
    },
    updateOrdersTotal() {
      this.ordersTotalPrice = this.selectedOrderItems
        .reduce((total, item) => total + (item.totalPrice / 100), 0)
        .toFixed(2);
    },
    isNewActivity(createTime) {
      if (!createTime) return false;
      const createDate = new Date(createTime);
      const now = new Date();
      const diffDays = (now - createDate) / (1000 * 60 * 60 * 24);
      return diffDays <= 7;
    },
    formatDate(date) {
      if (!date) return '未知';
      const d = new Date(date);
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
    },
    getOrderStatusText(status) {
      switch (status) {
        case 1: return '已报名';
        case 2: return '已取消报名';
        default: return '未知';
      }
    },
  },
};
</script>

<style scoped>
.container.dark-theme {
  background: radial-gradient(ellipse at center, #001e3c 0%, #000 100%);
  min-height: 100vh;
  color: #fff;
  font-family: 'Microsoft YaHei', sans-serif;
}

.header {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #002d52;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.back-button {
  cursor: pointer;
  color: #4fc3f7;
  font-size: 16px;
}

.back-button:hover {
  color: #999;
}

.title {
  margin-left: 20px;
  font-size: 20px;
  color: #fff;
  flex: 1;
}

.organizer-section {
  padding: 20px;
}

.organizer-info {
  background: rgba(0, 45, 82, 0.8);
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.organizer-image {
  width: 100%;
  max-width: 400px;
  height: 300px;
}

.organizer-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.organizer-details {
  flex: 1;
}

.organizer-details h2 {
  margin: 0 0 10px;
  color: #fff;
  font-size: 24px;
}

.organizer-details .description {
  color: #e0e0e0;
  margin: 0 0 10px;
  font-size: 16px;
  line-height: 1.6;
}

.organizer-details .contact,
.organizer-details .address {
  color: #b0bec5;
  margin: 0 0 10px;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.organizer-details .contact i,
.organizer-details .address i {
  margin-right: 5px;
}

.content {
  padding: 20px;
}

.activity-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: flex-start;
}

.activity-card {
  background: rgba(0, 45, 82, 0.8);
  border-radius: 8px;
  overflow: hidden;
  transition: transform 0.3s;
  display: flex;
  flex-direction: column;
  cursor: pointer;
  width: 300px;
  min-height: 400px;
}

.activity-card:hover {
  transform: translateY(-5px);
}

.activity-image {
  position: relative;
  width: 100%;
  height: 200px;
}

.activity-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.special-tag,
.sold-out-tag {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.special-tag {
  background: #f56c6c;
  color: #fff;
}

.sold-out-tag {
  background: #909399;
  color: #fff;
}

.activity-info {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.activity-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.activity-header h3 {
  margin: 0;
  color: #fff;
  font-size: 18px;
  flex: 1;
}

.price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
  margin-left: 10px;
}

.original-price {
  color: #b0bec5;
  font-size: 14px;
  text-decoration: line-through;
  margin-left: 5px;
}

.store-info {
  color: #b0bec5;
  font-size: 14px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.store-info i {
  margin-right: 5px;
}

.activity-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.tags {
  display: flex;
  gap: 5px;
}

.tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.tag.special {
  background: #f56c6c;
  color: #fff;
}

.tag.new {
  background: #67c23a;
  color: #fff;
}

.tag.hot {
  background: #e6a23c;
  color: #fff;
}

.el-button {
  background: #003b64;
  border: 1px solid #4fc3f7;
  color: #4fc3f7;
}

.el-button:hover:not(:disabled) {
  background: #4fc3f7;
  color: #fff;
}

.el-button:disabled {
  background: #909399;
  border-color: #909399;
  color: #fff;
  cursor: not-allowed;
}

.orders-dialog {
  background: #001e3c;
}

.orders-dialog .el-dialog__title {
  color: #fff;
}

.activity-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.orders-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 20px;
  padding: 20px;
  background: #002d52;
  border-radius: 4px;
}

.total-price {
  font-size: 20px;
  color: #4fc3f7;
  margin-right: 20px;
}

.stock {
  color: #e0e0e0;
  font-size: 14px;
  margin-bottom: 10px;
}
</style>
